import React, { useEffect, useState } from 'react'
import { Button, message } from 'antd'
import BraftEditor from 'braft-editor'
import 'braft-editor/dist/index.css'
import styles from './index.module.less'
// import { uploadImageFileApi } from '@/request/api'
import { debounce } from '@/utils/func'

function Braft({ initContent = '', getContent, buttonLabel = '提交' }) {
  const [editorState, setEditorState] = useState(
    BraftEditor.createEditorState(initContent)
  )

  useEffect(() => {
    setEditorState(BraftEditor.createEditorState(initContent))
  }, [initContent])

  // 防抖
  // const debounceSetState = debounce((newState) => setEditorState(newState), 300)
  // 当内容改变了，进行防抖更新
  const handleEditorChange = (newEditorState) => {
    // debounceSetState(newEditorState)
    setEditorState(newEditorState)
  }

  // 上传图片的处理函数
  const myUploadFn = async (param) => {
    const formData = new FormData()
    formData.append('file', param.file)

    // try {
    //   const res = await uploadImageFileApi(formData)
    //   console.log(res)
    //   if (res.status === 201 || res.status === 200)
    //     message.success('上传成功！')
    //   else return message.error('上传失败')

    //   param.success({
    //     url: res.data.path,
    //     meta: {
    //       id: res.data.filename,
    //       title: res.data.originalname,
    //       alt: res.data.filename,
    //       loop: false,
    //       autoPlay: false,
    //       controls: true,
    //       poster: res.data.path,
    //     },
    //   })
    // } catch (err) {
    //   return { error: { message: '上传失败2323' } } // 如果上传失败，返回 error
    // }
  }

  // 导出编辑器内容
  const submit = () => {
    // getContent(editorState.toHTML())
    // console.log(editorState.toHTML())
    // console.log(editorState)
    getContent({ raw: editorState.toRAW(), html: editorState.toHTML() })
  }

  return (
    <div className={styles.BraftEditorContainer}>
      <div className={styles.BraftEditor}>
        <BraftEditor
          value={editorState}
          placeholder="请输入内容"
          onChange={handleEditorChange}
          // media={{ uploadFn: myUploadFn }}
        ></BraftEditor>
      </div>

      {/* 提交按钮 */}
      <div className={styles.submitBtn}>
        <Button type="primary" onClick={submit}>
          {buttonLabel}
        </Button>
      </div>
    </div>
  )
}

import ErrorBoundary from '@/components/ErrorBoundary'
const sourceComponent = 'BraftEditor'
const BraftEB = ErrorBoundary(Braft, sourceComponent)
export default BraftEB
